import React, { Component } from 'react';

class FormInput extends Component {

    static defaultProps = {
        className: [],
        labelClassName: [],
        inputClassName: [],
        label: '',
        name: '',
        dataItem: {},
        type: 'text',
        disabled: false,
        onChange: () => { }
    };

    state = {
        inputValue: this.props.dataItem[this.props.name]
    };

    componentWillReceiveProps = (props) => {
        let { dataItem, name } = props;
        let { inputValue } = this.state;
        if (dataItem[name] && dataItem[name] !== inputValue) {
            inputValue = dataItem[name];
            this.setState({ inputValue });
        }
    };

    render() {
        const {
            extra
        } = this.props;
        return (
            <div className={['form-group'].concat(this.props.className).join(' ')}>
                <label className={["control-label"].concat(this.props.labelClassName).join(' ')} style={{ "marginTop": "5px", "marginRight": "5px" }}>{this.props.label}:</label>
                <input readOnly={this.props.readOnly} disabled={this.props.disabled} type={this.props.type} className={["form-control"].concat(this.props.inputClassName).join(' ')} name={this.props.name} value={this.state.inputValue} onChange={this._onChange} />
                { extra ? extra : null }
            </div>
        );
    }

    _onChange = (evt) => {
        let { dataItem, name } = this.props;
        dataItem[name] = evt.target.value;
        if (global.isDebug) {
            console.log(`${dataItem} ${name} => ${dataItem[name]}`);
        }
        this.setState({ inputValue: dataItem[name] });
        this.props.onChange(dataItem[name], name);
    };
}

export default FormInput;